package ui;

import dao.DataChangeListener;
import dao.DataManager;
import java.awt.*;
import java.util.List;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import model.ClassRoom;
import model.Group;
import model.Student;

public class GroupManagementPanel extends JPanel implements DataChangeListener {
    private JTable groupTable;
    private DefaultTableModel tableModel;
    
    public GroupManagementPanel() {
        setLayout(new BorderLayout());
        initComponents();
        DataManager.getInstance().addDataChangeListener(this);
    }
    
    private void initComponents() {
        // 创建表格
        String[] columnNames = {"ID", "小组名称", "得分"};
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        groupTable = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(groupTable);
        
        // 创建按钮
        JPanel buttonPanel = new JPanel();
        JButton addButton = new JButton("新增小组");
        JButton editButton = new JButton("编辑小组");
        JButton deleteButton = new JButton("删除小组");
        JButton scoreButton = new JButton("评分");
        
        buttonPanel.add(addButton);
        buttonPanel.add(editButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(scoreButton);
        
        // 添加到面板
        add(scrollPane, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);
        
        // 添加事件监听
        addButton.addActionListener(e -> showAddDialog());
        editButton.addActionListener(e -> showEditDialog());
        deleteButton.addActionListener(e -> deleteGroup());
        scoreButton.addActionListener(e -> showScoreDialog());
        
        // 刷新表格
        refreshGroupTable();
    }
    
    @Override
    public void onDataChanged() {
        refreshGroupTable();
    }
    
    private void refreshGroupTable() {
        tableModel.setRowCount(0);
        for (Group group : DataManager.getInstance().getAllGroups()) {
            tableModel.addRow(new Object[]{
                group.getId(),
                group.getName(),
                group.getScore()
            });
        }
    }
    
    private void showAddDialog() {
        JDialog dialog = new JDialog((Frame)SwingUtilities.getWindowAncestor(this), "新增小组", true);
        dialog.setLayout(new BorderLayout(5, 5));
        
        // 创建输入面板
        JPanel inputPanel = new JPanel(new GridLayout(2, 2, 5, 5));
        JTextField nameField = new JTextField();
        inputPanel.add(new JLabel("小组名称:"));
        inputPanel.add(nameField);
        
        // 创建班级选择面板
        JPanel classPanel = new JPanel(new GridLayout(2, 1, 5, 5));
        JComboBox<ClassRoom> classComboBox = new JComboBox<>();
        for (ClassRoom classroom : DataManager.getInstance().getAllClasses()) {
            classComboBox.addItem(classroom);
        }
        classPanel.add(new JLabel("选择班级："));
        classPanel.add(classComboBox);
        
        // 修改学生选择面板
        JPanel studentPanel = new JPanel(new BorderLayout(5, 5));
        DefaultListModel<Student> studentListModel = new DefaultListModel<>();
        JList<Student> studentList = new JList<>(studentListModel);
        
        // 使用CTRL键进行多选
        studentList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        
        // 添加提示标签
        JLabel tipLabel = new JLabel("按住Ctrl键可选择两名学生");
        tipLabel.setForeground(Color.BLUE);
        
        studentList.addListSelectionListener(e -> {
            if (!e.getValueIsAdjusting()) {
                List<Student> selected = studentList.getSelectedValuesList();
                if (selected.size() > 2) {
                    studentList.clearSelection();
                    JOptionPane.showMessageDialog(dialog, "最多只能选择两名学生！");
                }
            }
        });
        
        classComboBox.addActionListener(e -> {
            studentListModel.clear();
            if (classComboBox.getSelectedItem() != null) {
                ClassRoom selectedClass = (ClassRoom) classComboBox.getSelectedItem();
                List<Student> students = DataManager.getInstance().getStudentsByClass(selectedClass.getId());
                for (Student student : students) {
                    if (student.getGroupId() == 0) { // 只显示未分组的学生
                        studentListModel.addElement(student);
                    }
                }
            }
        });
        
        JPanel studentHeaderPanel = new JPanel(new GridLayout(2, 1));
        studentHeaderPanel.add(new JLabel("选择学生（必须选择两名学生）："));
        studentHeaderPanel.add(tipLabel);
        
        studentPanel.add(studentHeaderPanel, BorderLayout.NORTH);
        studentPanel.add(new JScrollPane(studentList), BorderLayout.CENTER);
        
        // 创建按钮面板
        JPanel buttonPanel = new JPanel();
        JButton confirmButton = new JButton("确定");
        confirmButton.addActionListener(e -> {
            if (nameField.getText().trim().isEmpty()) {
                JOptionPane.showMessageDialog(dialog, "小组名称不能为空！");
                return;
            }
            
            if (studentList.getSelectedValuesList().size() != 2) {
                JOptionPane.showMessageDialog(dialog, "请选择两名学生！");
                return;
            }
            
            int newId = DataManager.getInstance().getAllGroups().size() + 1;
            Group newGroup = new Group(newId, nameField.getText(), 0);
            DataManager.getInstance().addGroup(newGroup);
            
            // 更新选中学生的小组ID
            for (Student student : studentList.getSelectedValuesList()) {
                student.setGroupId(newId);
                DataManager.getInstance().updateStudent(student);
            }
            
            refreshGroupTable();
            dialog.dispose();
        });
        
        buttonPanel.add(confirmButton);
        buttonPanel.add(new JButton("取消") {{ addActionListener(e -> dialog.dispose()); }});
        
        // 组装对话框
        JPanel mainPanel = new JPanel(new BorderLayout(5, 5));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        mainPanel.add(inputPanel, BorderLayout.NORTH);
        mainPanel.add(classPanel, BorderLayout.CENTER);
        mainPanel.add(studentPanel, BorderLayout.SOUTH);
        
        dialog.add(mainPanel, BorderLayout.CENTER);
        dialog.add(buttonPanel, BorderLayout.SOUTH);
        
        dialog.pack();
        dialog.setLocationRelativeTo(this);
        dialog.setVisible(true);
    }
    
    private void showEditDialog() {
        int selectedRow = groupTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请先选择要编辑的小组！");
            return;
        }
        
        int id = (int) tableModel.getValueAt(selectedRow, 0);
        String currentName = (String) tableModel.getValueAt(selectedRow, 1);
        int currentScore = (int) tableModel.getValueAt(selectedRow, 2);
        
        JDialog dialog = new JDialog((Frame)SwingUtilities.getWindowAncestor(this), "编辑小组", true);
        dialog.setLayout(new GridLayout(4, 2, 5, 5));
        
        JTextField nameField = new JTextField(currentName);
        JSpinner scoreSpinner = new JSpinner(new SpinnerNumberModel(currentScore, 0, 100, 1));
        
        dialog.add(new JLabel("小组名称:"));
        dialog.add(nameField);
        dialog.add(new JLabel("小组得分:"));
        dialog.add(scoreSpinner);
        
        JButton confirmButton = new JButton("确定");
        confirmButton.addActionListener(e -> {
            if (nameField.getText().trim().isEmpty()) {
                JOptionPane.showMessageDialog(dialog, "小组名称不能为空！");
                return;
            }
            
            Group updatedGroup = new Group(id, nameField.getText(), 0);
            updatedGroup.setScore((int)scoreSpinner.getValue());
            DataManager.getInstance().updateGroup(updatedGroup);
            refreshGroupTable();
            dialog.dispose();
        });
        
        dialog.add(confirmButton);
        dialog.add(new JButton("取消") {{ addActionListener(e -> dialog.dispose()); }});
        
        dialog.pack();
        dialog.setLocationRelativeTo(this);
        dialog.setVisible(true);
    }
    
    private void deleteGroup() {
        int selectedRow = groupTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请先选择要删除的小组！");
            return;
        }
        
        int id = (int) tableModel.getValueAt(selectedRow, 0);
        int confirm = JOptionPane.showConfirmDialog(this, 
            "确定要删除这个小组吗？", "确认删除", 
            JOptionPane.YES_NO_OPTION);
            
        if (confirm == JOptionPane.YES_OPTION) {
            DataManager.getInstance().removeGroup(id);
            refreshGroupTable();
        }
    }
    
    private void showScoreDialog() {
        int selectedRow = groupTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请先选择要评分的小组！");
            return;
        }
        
        int id = (int) tableModel.getValueAt(selectedRow, 0);
        String name = (String) tableModel.getValueAt(selectedRow, 1);
        int currentScore = (int) tableModel.getValueAt(selectedRow, 2);
        
        JDialog dialog = new JDialog((Frame)SwingUtilities.getWindowAncestor(this), "小组评分", true);
        dialog.setLayout(new GridLayout(3, 2, 5, 5));
        
        JSpinner scoreSpinner = new JSpinner(new SpinnerNumberModel(currentScore, 0, 100, 1));
        
        dialog.add(new JLabel("小组名称:"));
        dialog.add(new JLabel(name));
        dialog.add(new JLabel("分数:"));
        dialog.add(scoreSpinner);
        
        JButton confirmButton = new JButton("确定");
        confirmButton.addActionListener(e -> {
            int score = (int) scoreSpinner.getValue();
            Group group = new Group(id, name, 0);
            group.setScore(score);
            DataManager.getInstance().updateGroup(group);
            refreshGroupTable();
            dialog.dispose();
        });
        
        dialog.add(confirmButton);
        dialog.add(new JButton("取消") {{ addActionListener(e -> dialog.dispose()); }});
        
        dialog.pack();
        dialog.setLocationRelativeTo(this);
        dialog.setVisible(true);
    }
} 